//
//  HDCFRedemptionPageVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/20.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFRedemptionPageVc.h"
#import "HDCFFundCell.h"
#import "makeUpTableViewCell.h"
#import "jijinAndGroupDetailModel.h"
#import "shuhuiSuccessViewController.h"
#import "InputPassWordView.h"
#import "shuhuiResultModel.h"
#import "HDCFMyBankCardVc.h"
#define KBankCardInfo @"/public/transaction/get-investor-payment-method"


@interface HDCFRedemptionPageVc ()<UITableViewDelegate, UITableViewDataSource,InputPassWordViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *cankaofeilv;
@property (weak, nonatomic) IBOutlet UILabel *yujiFeiyong;
@property (weak, nonatomic) IBOutlet UILabel *bankInfo;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *feeRate;
@property (weak, nonatomic) IBOutlet UILabel *costMoney;
@property (weak, nonatomic) IBOutlet UITableView *fundTabel;

@property (nonatomic, weak) UIView *hitView;
@property(nonatomic,strong)UIView *clearHudView;


@property (nonatomic, strong) NSDictionary *bankDetail;
@property (nonatomic, strong) NSArray *bankArray;
@property (nonatomic, copy) NSString *tradePassword;
@property (nonatomic, copy) NSString *investorPayId;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *costLabelConst;

@property (nonatomic, assign) BOOL isBankCard;;


@end

@implementation HDCFRedemptionPageVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title=self.titleStr;
    self.moneyLabel.text=[NSString stringWithFormat:@"%.2f元",self.zichanXianzhiZong];
    self.fundTabel.rowHeight=75;
    self.fundTabel.delegate = self;
    self.fundTabel.dataSource = self;
    self.fundTabel.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.fundTabel.separatorColor = ZKcolor(245, 245, 245);
    
    [self.fundTabel registerNib:[UINib nibWithNibName:@"makeUpTableViewCell" bundle:nil] forCellReuseIdentifier:@"makeUpTableViewCell"];
    
    [self initData];
    [self configerTableFooterView];
    
    if (self.zichanType==1) {
        self.costMoney.hidden=YES;
        self.yujiFeiyong.hidden=YES;
//        _cankaofeilv.hidden = YES;
//        _feeRate.hidden = YES;
        [self getZuheData];
    }
    else
    {
        [self getJinData];
    }
    
}

-(void)configerTableFooterView
{
    UIButton *btnTwoYF = [[UIButton alloc] init];
    btnTwoYF.frame = CGRectMake(0, 0, screenWidth, 50);
    [btnTwoYF setBackgroundColor:ZKcolor(245, 245, 245)];
    NSString *strleft = @"基金销售服务由奕丰金融提供\n-基金有风险 投资需谨慎-";
    NSMutableAttributedString *attrStrT = [[NSMutableAttributedString alloc] initWithString:strleft];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:[UIColor lightGrayColor]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:12]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:14]
                     range:NSMakeRange(7, 4)];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:ZKcolor(33, 33, 33)
                     range:NSMakeRange(7, 4)];
    [btnTwoYF setAttributedTitle:attrStrT forState:UIControlStateNormal];
    [btnTwoYF setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnTwoYF.titleLabel setTextAlignment:NSTextAlignmentCenter];
    btnTwoYF.titleLabel.lineBreakMode = 0;
    [btnTwoYF addTarget:self action:@selector(presentPage) forControlEvents:UIControlEventTouchUpInside];
    [self.fundTabel setTableFooterView:btnTwoYF];
    
}


- (void)presentPage{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *view = [[UIView alloc] init];
    self.clearHudView = view;
    view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
    UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
    r5.numberOfTapsRequired = 1;
    [view addGestureRecognizer:r5];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(30, (screenHeight - (screenWidth - 60) * 900.0 / 500.0) / 2, screenWidth - 60, (screenWidth - 60) * 900.0 / 500.0);
    imageView.image = [UIImage imageNamed:@"661511947049_.pic_hd.jpg"];
    [view addSubview:imageView];
    view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [window addSubview:view];
}

- (void)viewHit{
    [self.clearHudView removeFromSuperview];
}
- (IBAction)chooseBanck:(UIButton *)sender {
    
    HDCFMyBankCardVc*vc=[[HDCFMyBankCardVc alloc]init];
    vc.isNeedBlock=YES;
    vc.isXianshiWallet=YES;
    vc.isHiddenDeleteBtn = YES;
    vc.block = ^(NSString *name, NSString *bank, NSString *bankId,BOOL isBankCard) {
        self.isBankCard=isBankCard;
        if (isBankCard==YES) {
            self.investorPayId=bankId;
            self.bankInfo.text = [NSString stringWithFormat:@"%@ *** %@", name, bank];
        }
        else
        {
            self.bankInfo.text = [NSString stringWithFormat:@"现金钱包 余额：%@",  name];
        }
        
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
    [SVProgressHUD dismissWithDelay:1.0];
    
}


-(void)configerBottomView
{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, screenHeight - 49 , screenWidth, 49);
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"确认赎回" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(jumpBuy) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:ZKcolor(184, 27, 36)];
    [self.view addSubview:btn];
}

-(void)jumpBuy
{
    [self alertPasswordView];
//    shuhuiSuccessViewController*vc=[[shuhuiSuccessViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getJinData
{
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    if (self.code) {
        paramets[@"fundCode"] = self.code;
    }
    if (self.shuhuiFenShu) {
        paramets[@"redemptionUnit"] = self.shuhuiFenShu;
    }
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/transaction/get-sell-fee-and-charge"};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSLog(@"%@",result);
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDict = result[@"data"];
            if (dataDict&&![dataDict isEqual:[NSNull null]]) {
                [self configerBottomView];
                if ([self.chargeMode isEqualToString:@"0"]) {
                    self.feeRate.text=[NSString stringWithFormat:@"%@%%",dataDict[@"avgRedemptionChargeRate"]];
                    self.costMoney.text=[NSString stringWithFormat:@"%.2f元",[dataDict[@"redemptionCharge"] floatValue]];
                }
                else if ([self.chargeMode isEqualToString:@"1"])
                {
                    self.feeRate.text=[NSString stringWithFormat:@"%@%%",dataDict[@"backendRate"]];
                    self.costMoney.text=[NSString stringWithFormat:@"%.2f元",[dataDict[@"backendCharges"] floatValue]];
                }
 
            }
            
        }

        
    } failure:^(NSError *errer) {
        
    }];
    
}

- (void)initData{
    
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/find-bank"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSDictionary *dict = result[@"data"];
        self.bankArray = [NSArray arrayWithArray:dict[@"data"]];
        LSWeakSelf;
        [weakSelf getBankCardInfo];
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)getBankCardInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KBankCardInfo};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDict = result[@"data"];
            
            NSLog(@"%@",result);
            
            NSDictionary *investorBankDetails = dataDict[@"investorBankDetails"];
            NSArray *bankArrayt = investorBankDetails[@"data"];
            NSDictionary *bankDetail = bankArrayt.firstObject;
            self.bankDetail = bankDetail;
            self.investorPayId =self.bankDetail[@"investorPayId"];
//            NSString *imageName = [NSString stringWithFormat:@"icon_%@", bankDetail[@"bankCode"]];
//            self.bankIcon.image = [UIImage imageNamed:imageName];
            for (int i = 0; i < self.bankArray.count; i++) {
                NSDictionary *dict = self.bankArray[i];
                if ([bankDetail[@"bankCode"] isEqualToString:dict[@"bankCode"]]) {
//                    NSString *banName = dict[@"bankName"];
                    NSString *cardNo = bankDetail[@"bankNumber"];
                    NSString *laterFour = [cardNo substringFromIndex:(cardNo.length - 4)];
                    self.investorPayId=[NSString stringWithFormat:@"%@",bankDetail[@"investorPayId"]];
                    self.bankInfo.text = [NSString stringWithFormat:@"%@ 尾号 (%@)", dict[@"bankName"], laterFour];
                    break;
                }
            }
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"获取银行卡信息失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

-(void)getZuheData
{
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
     paramets[@"accountNumber"] = kAcount;
    if (self.code) {
        paramets[@"portfolioId"] = self.code;
    }
    
//    paramets[@"accountNumber"] = self.shuhuiFenShu;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/product/portfolio/redeem-portfolio-transaction-fee"};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSLog(@"%@",result);
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDict = result[@"data"];
            if (dataDict&&![dataDict isEqual:[NSNull null]]) {
                [self configerBottomView];
            
            self.cankaofeilv.text=@"预计费用";
            self.feeRate.text=[NSString stringWithFormat:@"%.2f元",[dataDict[@"totalRedemptionCharge"] floatValue]];
            }
        }
        
    } failure:^(NSError *errer) {
        
    }];
    
}

-(void)alertPasswordView
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *view = [[UIView alloc] init];
    self.hitView = view;
    UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
    r5.numberOfTapsRequired = 1;
    [view addGestureRecognizer:r5];
    
    view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
    view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    InputPassWordView *inputView = [InputPassWordView InputPassWordView];
    inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
    inputView.layer.cornerRadius = 5.0;
    inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
    inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
    inputView.layer.shadowRadius = 3;//阴影半径，默认3
    inputView.clipsToBounds = YES;
    inputView.delegate = self;
    
    [view addSubview:inputView];
    [window addSubview:view];
}


- (void)cancelClick{
    [self.hitView removeFromSuperview];
}

- (void)confirmClickWithPassWord:(NSString *)password{
    self.tradePassword = password;
    [self.hitView removeFromSuperview];
    
    if (self.zichanType==2) {
        [self shuhuiJijin];
    }
    else if (self.zichanType==1)
    {
        [self shuhuizuhe];
    }
    else if (self.zichanType==3)
    {
        [self shuhuilicai];
    }

    [SVProgressHUD show];

}

-(void)shuhuiJijin
{
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
//
    paramets[@"password"] = self.tradePassword;
    if (self.isBankCard==YES) {
        paramets[@"payMethod"] = @"0";
         paramets[@"investorPayId"] = self.investorPayId;
    }
    else
    {
        paramets[@"payMethod"] = @"1";
    }
    NSMutableArray*sellFundsArray=[NSMutableArray array];
    
    
    for (jijinAndGroupDetailModel*model in self.modelArray) {
        NSMutableDictionary*dic=[NSMutableDictionary dictionary];
        dic[@"fundCode"] = model.fundCode;
        dic[@"redemptionUnit"] = model.availableUnit;
        [sellFundsArray addObject:dic];
        
    }
    [paramets setObject:sellFundsArray forKey:@"sellFunds"];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/transaction/redeem-fund-transaction"};
    [HttpRequest sendPostRequestWithURL:nil WithParamets:paramet WithJsonString:jsonStr success:^(id result) {
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dataDict = result[@"data"];
            shuhuiResultModel*model=[shuhuiResultModel mj_objectWithKeyValues:dataDict];
            NSLog(@"%@",result);
            shuhuiSuccessViewController*vc=[[shuhuiSuccessViewController alloc]init];
            vc.shuhuiModel=model;
            vc.zichanType=self.zichanType;
            [self.navigationController pushViewController:vc animated:YES];

            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }

    } failure:^(NSError *errer) {
        
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

-(void)shuhuizuhe
{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
//    paramets[@"investorPayId"] = self.investorPayId;
    paramets[@"password"] = self.tradePassword;
    if (self.isBankCard==YES) {
        paramets[@"payMethod"] = @"0";
         paramets[@"investorPayId"] = self.investorPayId;
    }
    else
    {
        paramets[@"payMethod"] = @"1";
    }
    paramets[@"portfolioId"] = self.code;

    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"methodPath"] = @"/public/product/portfolio/redeem-portfolio-transaction";
    dict[KparametOne] = [self dictionaryToJson:paramets];
    
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dict WithJsonString:jsonStr success:^(id result) {
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dataDict = result[@"data"];
            shuhuiResultModel*model=[shuhuiResultModel mj_objectWithKeyValues:dataDict];
            NSLog(@"%@",result);
            shuhuiSuccessViewController*vc=[[shuhuiSuccessViewController alloc]init];
            vc.shuhuiModel=model;
            vc.zichanType=self.zichanType;
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }
        
        else
        {
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
    }];
}


-(void)shuhuilicai
{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
//    paramets[@"investorPayId"] = self.investorPayId;
    paramets[@"password"] = self.tradePassword;
    if (self.isBankCard==YES) {
        paramets[@"sellMode"] = @"0";
        paramets[@"investorPayId"] = self.investorPayId;
    }
    else
    {
       paramets[@"sellMode"] = @"1";
    }
    
    paramets[@"fundCode"] = self.code;
    paramets[@"redemptionUnit"] = self.code;
    for (jijinAndGroupDetailModel*model in self.modelArray) {
        paramets[@"redemptionUnit"] = model.availableUnit;
        
    }
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/product/collective/redeem-collective-transaction"};
    [HttpRequest sendPostRequestWithURL:nil WithParamets:paramet WithJsonString:jsonStr success:^(id result) {
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dataDict = result[@"data"];
            shuhuiResultModel*model=[shuhuiResultModel mj_objectWithKeyValues:dataDict];
            NSLog(@"%@",result);
            shuhuiSuccessViewController*vc=[[shuhuiSuccessViewController alloc]init];
            vc.shuhuiModel=model;
            vc.zichanType=self.zichanType;
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }
        
        else
        {
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
    }];
}



- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    makeUpTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"makeUpTableViewCell" forIndexPath:indexPath];
    jijinAndGroupDetailModel*model=self.modelArray[indexPath.row];
    
    NSLog(@"%@",model.currentValue);
    cell.name.text=model.fundName;
    cell.shouyi.text=[NSString stringWithFormat:@"%.2f%%",[model.currentValue floatValue]/self.zichanXianzhiZong*100];
    cell.numStyle.text=[NSString stringWithFormat:@"%@",model.fundCode];
    cell.zhanbi.text=[NSString stringWithFormat:@"赎回份额:%.2f份",[model.availableUnit floatValue]];
    cell.shouyi.textColor=COLOR_NAV;
    cell.zhanbi.textColor=[UIColor blackColor];
    
    return cell;

}

@end
